const Order = require('../models/Order')
const Cart = require('../models/Cart')
const Product = require('../models/Product')
const Response = require('../utils/response')
const { validationResult } = require('express-validator')

// 创建订单
exports.createOrder = async (req, res) => {
  try {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return Response.error(res, errors.array()[0].msg, 400)
    }

    const userId = req.userId
    const { products, address } = req.body

    // 验证商品和计算总价
    let totalAmount = 0
    const orderProducts = []

    for (let item of products) {
      const product = await Product.findById(item.productId || item.product_id)
      
      if (!product) {
        return Response.error(res, `商品${item.productId || item.product_id}不存在`, 400)
      }

      if (product.stock < item.quantity) {
        return Response.error(res, `商品"${product.name}"库存不足`, 400)
      }

      // 减少库存
      await Product.decreaseStock(product.id, item.quantity)
      
      // 增加销量
      await Product.increaseSales(product.id, item.quantity)

      const itemTotal = product.price * item.quantity
      totalAmount += itemTotal

      orderProducts.push({
        id: product.id,
        product_id: product.id,
        name: product.name,
        product_name: product.name,
        price: product.price,
        quantity: item.quantity,
        image: product.image,
        product_image: product.image
      })
    }

    // 创建订单 (totalAmount, actualAmount, address)
    const actualAmount = totalAmount // 实付金额等于总额（暂无优惠）
    const result = await Order.create(userId, orderProducts, totalAmount, actualAmount, address)

    // 清空购物车中的选中商品（可选）
    await Cart.deleteSelected(userId)

    return Response.success(res, result, '订单创建成功')
  } catch (error) {
    console.error('创建订单错误:', error)
    return Response.error(res, '创建订单失败', 500)
  }
}

// 获取订单列表
exports.getOrderList = async (req, res) => {
  try {
    const userId = req.userId
    const { page = 1, limit = 10, status } = req.query

    console.log('📋 获取订单列表 - 参数:', { userId, page, limit, status })

    const result = await Order.getOrdersByUserId(
      userId,
      parseInt(page),
      parseInt(limit),
      status
    )

    console.log('✅ 订单列表查询成功:', {
      订单数量: result.orders.length,
      总数: result.pagination.total
    })

    return Response.success(res, result)
  } catch (error) {
    console.error('❌ 获取订单列表错误:', error)
    console.error('错误堆栈:', error.stack)
    return Response.error(res, '查询订单列表失败', 500)
  }
}

// 获取订单详情
exports.getOrderDetail = async (req, res) => {
  try {
    const userId = req.userId
    const { id } = req.params

    const order = await Order.findById(id, userId)

    if (!order) {
      return Response.notFound(res, '订单不存在')
    }

    return Response.success(res, order)
  } catch (error) {
    console.error('获取订单详情错误:', error)
    return Response.error(res, '获取订单详情失败', 500)
  }
}

// 根据订单号获取订单
exports.getOrderByNo = async (req, res) => {
  try {
    const userId = req.userId
    const { orderNo } = req.params

    const order = await Order.findByOrderNo(orderNo, userId)

    if (!order) {
      return Response.notFound(res, '订单不存在')
    }

    return Response.success(res, order)
  } catch (error) {
    console.error('获取订单错误:', error)
    return Response.error(res, '获取订单失败', 500)
  }
}

// 更新订单状态
exports.updateOrderStatus = async (req, res) => {
  try {
    const userId = req.userId
    const { id } = req.params
    const { status } = req.body

    // 验证状态值
    const validStatuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled']
    if (!validStatuses.includes(status)) {
      return Response.error(res, '无效的订单状态', 400)
    }

    const result = await Order.updateStatus(id, userId, status)

    if (result.affectedRows === 0) {
      return Response.notFound(res, '订单不存在')
    }

    return Response.success(res, null, '状态更新成功')
  } catch (error) {
    console.error('更新订单状态错误:', error)
    return Response.error(res, '更新失败', 500)
  }
}

// 取消订单
exports.cancelOrder = async (req, res) => {
  try {
    const userId = req.userId
    const { id } = req.params

    const result = await Order.cancel(id, userId)

    if (result.affectedRows === 0) {
      return Response.error(res, '订单不存在或无法取消', 400)
    }

    return Response.success(res, null, '订单已取消')
  } catch (error) {
    console.error('取消订单错误:', error)
    return Response.error(res, '取消订单失败', 500)
  }
}

// 删除订单
exports.deleteOrder = async (req, res) => {
  try {
    const userId = req.userId
    const { id } = req.params

    const result = await Order.delete(id, userId)

    if (result.affectedRows === 0) {
      return Response.error(res, '订单不存在或无法删除', 400)
    }

    return Response.success(res, null, '订单已删除')
  } catch (error) {
    console.error('删除订单错误:', error)
    return Response.error(res, '删除订单失败', 500)
  }
}

// 获取订单统计
exports.getOrderStats = async (req, res) => {
  try {
    const userId = req.userId
    const stats = await Order.getOrderStats(userId)

    return Response.success(res, stats)
  } catch (error) {
    console.error('获取订单统计错误:', error)
    return Response.error(res, '获取统计失败', 500)
  }
}



